const Domain ="https://yuehuiba.qiyedaishu.com";
//const Domain ="http://test.yuehuiba.qiyedaishu.com:12580";
//const Domain = "http://localhost:14838/";

import md5 from "@/utils/md5.js";
import validate from "@/utils/validate.js";
const FormatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(FormatNumber).join('/') + ' ' + [hour, minute, second].map(FormatNumber).join(':')
}

const FormatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
String.prototype.RHtml = function () {
  return this.replace(/<[^>]+>/g, "").replace(/&nbsp;/g, "");
};

String.prototype.ReplaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
};

String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};

String.prototype.Contain = function (str) {
    return this.indexOf(str)>-1?true:false;
};
String.prototype.FormLength = function () {
    var list = this.split('');
    var count=0;
    for(var i=0;i<list.length;i++)
    {
    	var item=list[i];
		if(validate.IsChinese(item)){
			count+=2;
		}else{
			count+=1;
		}
	}
	return count;
};
String.prototype.Cut = function (size) {
	if(this==""){
		return this;
	}
	var list = this.split('');
	var count=0;
	for(var i=0;i<list.length;i++)
	{
		var item=list[i];
		if(validate.IsNumber(item)){
			size-=0.5;
			count++;
		}
		else if(validate.IsLetter(item)){
			size-=0.5;
			count++;
		}
		else if(validate.IsChinese(item)){
			size-=1;
			count++;
		}else{
			size-=1;
			count++;
		}
		if(size<=0)
		{
			if(count>=size){
				return this.substring(0, count)+"...";
			}
		}
	}
	return this;
    
};
String.prototype.TranImg = function (str) {
    return this.ReplaceAll("<img","<img style='width:100%;' ");
};

String.prototype.TranImg = function (str) {
    return this.ReplaceAll("<img","<img style='width:100%;' ");
};
String.prototype.IsEmpty = function (str) {
    return (Validate.IsEmpty(str) || str==Domain);
};
String.prototype.ToSex = function () {
    if(this=="女"){
		return 'girl.png';
	}else{
		return 'boy.png';
	}
};
String.prototype.ToArray = function () {
	var array = [];
	this.split('-').forEach(item=>{
		array.push(parseInt(item));
	})
    return array;
};
String.prototype.ToList = function () {
	var array = [];
	this.split(',').forEach(item=>{
		if(item!=''){
			array.push(item);
		}
	})
    return array;
};
//过滤中文
String.prototype.FilterChinese = function () {
	var reg=/[\u4e00-\u9fa5a-zA-Z]/g;
	return this.replace(reg,'');
};
String.prototype.GetImg = function(size)
{		
    if (this.indexOf("tmp")>-1) {
    	return this;        
    }else{
    	var files = this.split('.');
    	if (files.length >= 2) {			
    	    var ext = "." + files[files.length - 1];
    	    return this.replace(ext, "") + "_" + size + ext;
    	} else {
    	    return this;
    	}
    }
}
Array.prototype.ToLabelValue = function () {
	var array = [];
	this.forEach(item=>{
		if(item!=''){
			array.push({label:item, value:item.FilterChinese()});
		}
	})
    return array;
};
Array.prototype.ToSameValue = function () {
	var array = [];
	this.forEach(item=>{
		if(item!=''){
			array.push({label:item, value:item});
		}
	})
    return array;
};
Array.prototype.Remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

Array.prototype.RemoveAt = function (index) {
    if (isNaN(index) || index >= this.length) {
        return false;
    }
    this.splice(index, 1);
};

Array.prototype.indexOf = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == val) return i;
  }
  return -1;
};

Array.prototype.Max = function () {
  return Math.max.apply(Math, this);
};

Array.prototype.Min = function () {
  return Math.min.apply(Math, this);
};

String.prototype.ToDate = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("yyyy-MM-dd");
};

String.prototype.ToTime = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("yyyy-MM-dd hh:mm");
};
String.prototype.ToDateTwo = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("yyyy.MM.dd");
};
String.prototype.ToDayTime = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("MM-dd hh:mm");
};
String.prototype.ReplacePlus = function () {
	var str=this;
	while(str.indexOf('+')>-1){
		str=str.replace('+','%2B');
	}
	return str;
};
String.prototype.ToMinute = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("hh:mm");
};
String.prototype.ToWeek = function () {
  const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const date = new Date(this.replace(/-/g, "/"));
  return weekday[date.getDay()];
};

Number.prototype.ToString = function () {
    if(this.toString()=='0'){
    	return '暂未填写';
    }else
    {
    	return this.toString();
    }
};
Number.prototype.ToEmpty = function () {
	if(this==0 || !this){
		return "";
	}else{
		return this+"";
	}
};
//四舍五入保留2位小数
Number.prototype.ToPrice = function () {
    return (Math.round(this * 100) / 100).toFixed(2);
};
Date.prototype.Format = function (format) {
  var o = {
    "M+": this.getMonth() + 1, //month 
    "d+": this.getDate(), //day 
    "h+": this.getHours(), //hour 
    "m+": this.getMinutes(), //minute 
    "s+": this.getSeconds(), //second 
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
    "S": this.getMilliseconds() //millisecond 
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};

Date.prototype.AddDays = function (d) {
    return new Date(this.setDate(this.getDate() + d));
};

String.prototype.ToString = function(){
	if(this.toString()==''){
		return '--';
	}else
	{
		return this;
	}
};

function Loading(title){
	uni.showLoading({
	    title: title
	});
};

function HideLoading(){
	uni.hideLoading();
};

function Toast(title, callback){
	uni.showToast({
	    title: title,
		icon: "none",
		position: "bottom",
	    duration: 3000,
		success: function (res) {
			setTimeout(function(){
				callback && callback();
			},1000);
		}
	});
};

function Success(title){
	uni.showToast({
	    title: title,
	    duration: 2000
	});
};

function Fail(title){
	uni.showToast({
	    title: title,
		image: "http://gongxianggudong.qiyedaishu.com/static/image/error.png",
	    duration: 2000
	});
};

function Alert(title, callback){
	uni.showModal({
	    title: "提示",
	    content: title,
		showCancel: false,
	    success: function (res) {
	        if (res.confirm) {
	            callback && callback();
	        } else if (res.cancel) {
	            
	        }
	    }
	});
}

function Confirm(title, callback){
	uni.showModal({
	    title: "提示",
	    content: title,
	    success: function (res) {
	        if (res.confirm) {
	            callback && callback();
	        } else if (res.cancel) {
	            
	        }
	    }
	});
}
function LoadMore(data,callback){
	Post(data, json=>{
		callback && callback(json.Data.List);
	});
}
function navigateTo(o){
	if(uni.getStorageSync("Token")){
		uni.navigateTo({
			url:o.url
		})
	}else{
		uni.navigateTo({
			url:'/pages/login/login'
		})
	}
};
function Post(data, callback) {
  data.ParentID=uni.getStorageSync("ParentID");
  data.Timestamp = new Date().getTime();
  data.Token =  uni.getStorageSync("Token") || '';
  data.Sign = md5.GetSign(data);
  uni.request({
		header: {'Content-Type':'application/x-www-form-urlencoded'},
  		url: Domain+"/tools/API.ashx",
		method:'POST',
  		data: data,
  		success: (json) => {
  			if(json.data.State){
  				callback && callback(json.data);
  			}else{
				if(json.data.Code=="401" && data.Act!="Find_MyData"){
					Toast(json.data.Msg, item=>{
						if(Ticker(2) && uni.getStorageSync("Cancel")=="false"){
							uni.navigateTo({
								url:'/pages/login/login'
							})
						}
					});
				}else{
					callback && callback(json.data);
				}
  			}
  		},
  		fail(json) {
  			Toast(json.data.Msg);
  		}
  });
};
function Ticker(Second){
	var OldTime = uni.getStorageSync("Time");
	if(!OldTime){
		uni.setStorageSync("Time",new Date().Format("yyyy-MM-dd hh:mm:ss"));
		return true;
	}else{
		var NewTime=new Date().Format("yyyy-MM-dd hh:mm:ss");
		uni.setStorageSync("Time",NewTime);
		if(DateDiff("s",OldTime, NewTime)>Second){
			return true;
		}else{
			return false;
		}
		
	}
};
function Upload(paths, handle, list, callback){
	var path = paths.pop();
	var token = uni.getStorageSync("Token") || '';
	if(path=='' || path.indexOf('/upload/')>-1 || path.indexOf('/img/')>-1){
		list.push(path);
		if(paths.length > 0){
			Upload(paths, handle, list, callback);
		}else{
			list.reverse();
			callback(list);
		}
	}else{		
		uni.uploadFile({
			  url: Domain + '/Tools/Upload.ashx', //仅为示例，非真实的接口地址
			  filePath: path,
			  name: 'img',
			  formData: {handle:handle, token:token},
			  success: json=> {
				  list.push(JSON.parse(json.data).Data.Path);
				  if(paths.length > 0){
					  Upload(paths, handle, list, callback);
				  }else{
					  list.reverse();
					  callback(list);
				  }
			  }
		});		
	}
};
function OneUpload(path, handle, callback){
	if(path=='' || path.indexOf('/upload/')>-1 || path.indexOf('/img/')>-1){
		if(callback){callback(path);}
	}else{				
		uni.uploadFile({
			  url: Domain + '/Tools/Upload.ashx', //仅为示例，非真实的接口地址
			  filePath: path,
			  name: 'img',
			  formData: {handle:handle},
			  success: json=> {
				  console.log(json);
				  if(callback){callback(JSON.parse(json.data));}
			  }
		});
	}
};

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return "";
};

function GCJ02ToBaiDu(value) {
    var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    var ll = value.split(",");
    var x = ll[1], y = ll[0];
    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
    return  (z * Math.sin(theta) + 0.006)+ ',' + (z * Math.cos(theta) + 0.0065);
};
function SetTabBarBadge(Count){
	if(Count>0){
		uni.setTabBarBadge({
			index: 3,
			text: Count.toString()
		});
		// #ifdef APP-PLUS
		plus.runtime.setBadgeNumber(Count);
		// #endif
	}else{
		uni.removeTabBarBadge({
			index:3
		});
	}
};
function ListToImgs(list){
	var array=[];
	list.forEach(item=>{
		array.push(item.Name+"*"+item.Path);
	});
	return array.join(",");
};
function ListToPaths(list){
	var array=[];
	list.forEach(item=>{
		array.push(item.Path);
	});
	return array.join(",");
};
function TranList(list){
	var array=[];
	list.forEach(item=>{
		array.push(item);
	});
	return array;
};

function CheckUpdate(){
	const updateManager = uni.getUpdateManager();
	updateManager.onCheckForUpdate(function (res) {
	  // 请求完新版本信息的回调
	});
	
	updateManager.onUpdateReady(function (res) {
	  uni.showModal({
	    title: '更新提示',
	    content: '发现新版本，点击确定后将重启？',
	    success(res) {
	      if (res.confirm) {
	        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
			
	        updateManager.applyUpdate();
	      }
	    }
	  });
	
	});
	
	updateManager.onUpdateFailed(function (res) {
	  // 新的版本下载失败
	});
};
function DateDiff(interval,date1,date2){
	var dt1 =  Date.parse(date1.replace(/-/g, '/'));
	var dt2 = Date.parse(date2.replace(/-/g, '/'));
	var long = parseInt(dt2 - dt1); //相差毫秒
	switch(interval.toLowerCase()){
	case "y": return parseInt(long/1000/60/60/24/365);
	case "m": return parseInt(long/1000/60/60/24/30);
	case "d": return parseInt(long/1000/60/60/24);
	case "w": return parseInt(long/1000/60/60/24/7);
	case "h": return parseInt(long/1000/60/60);
	case "n": return parseInt(long/1000/60);
	case "s": return parseInt(long/1000);
	case "l": return parseInt(long);
	}
}
function SetParam(options){
	//scene格式 UserID_ID
	if (options.scene) {
	    var scene = decodeURIComponent(options.scene);
		if(scene.indexOf("_")>-1){
			uni.setStorageSync("ParentID",scene.split('_')[0]);
		}else{
			uni.setStorageSync("ParentID",scene);
		}
	}
	if(options.ParentID){
		uni.setStorageSync("ParentID",decodeURIComponent(options.ParentID));
	}
};

function AdSkip(item){
	if(item.Type==0){
		uni.navigateTo({
			url:'/pages/ad/adinfo?ID='+item.ID
		})
	}
	else if(item.Type==1){
		uni.navigateTo({
			url:'/pages/active/activeinfo?ID='+item.SID
		})
	}else if(item.Type==2){
		uni.navigateTo({
			url:'/pages/yuehui/yuehuiinfo?ID='+item.SID
		})
	}else if(item.Type==3){
		uni.navigateTo({
			url:'/pages/matcher/matcherinfo?ID='+item.SID
		})
	}else if(item.Type==4){
		uni.navigateTo({
			url:'/pages/room/roominfo?ID='+item.SID
		})
	}
};
function Auth(){
	if(App.User.ID>0 && App.User.CardNum!='' && App.User.OpenIDF==''){
		Confirm("授权给鲸鸿飞书公众号以接收通知？",json=>{
			uni.navigateTo({
				url:'/pages/index/auth'
			})
		});
	}
};
function ToSuccess(Url, TipText, BtnText, Delta){
	uni.navigateTo({
		url:"/pages/index/success?Url="+Url+"&TipText="+TipText+"&BtnText="+BtnText+"&Delta="+Delta
	})
};
function ToPaySuccess(Url, Ewm, TipText, BtnText, Delta){
	uni.navigateTo({
		url:"/pages/index/paysuccess?Ewm="+Ewm+"&Url="+Url+"&TipText="+TipText+"&BtnText="+BtnText+"&Delta="+Delta
	})
};

function ClearForm(o){
	for (let key in o) {
	  if (o.hasOwnProperty(key) && typeof o[key] === 'string') {
		  if(o[key]=="0"){
			  o[key]="";
		  }
		  if(o[key]=="请选择"){
		  		o[key]="";
		  }
		  if(o[key]=="选择市"){
		  		o[key]="";
		  }
	  }
	}
	return o;
};
function GetMenuHeight() {	
	/*
	var menu = uni.getMenuButtonBoundingClientRect();
	var system = uni.getSystemInfoSync();
	return menu.height + (menu.top - system.statusBarHeight) * 2 + system.statusBarHeight 
	*/
   var menu = uni.getMenuButtonBoundingClientRect();
   let res = uni.getSystemInfoSync() ///微信api方法
   let titleH,height;
   if (res && res['system']) {
	   // 判断是否是安卓操作系统 （标题栏苹果为44px,安卓为48px）
	 if (res['system'].indexOf('Android') > 0) {
	   titleH = 48
	 } else {
	   titleH = 44
	 }
	 height = titleH + res['statusBarHeight'];	 
   }
   
   return {height: height, bottom:menu.top - res.statusBarHeight};
};
function AddPushCount(callback){
	if(uni.getStorageSync("Token")){
		var tmplid="-9h7QVAZE1BNRgepdF4YtoQKVylyeT2uPP8VP7OiAZ4";
		uni.requestSubscribeMessage({
			tmplIds: [tmplid],
			success: res=> {			
				if(JSON.stringify(res).indexOf("reject") != -1){
					if(callback){callback();}
					uni.openSetting({
					  success(res) {
						
					  }
					});
				} 
				if(JSON.stringify(res).indexOf("accept") != -1){
					uni.getSetting({
						withSubscriptions: true,
						success: res=> {					
							if(JSON.stringify(res.subscriptionsSetting).indexOf(tmplid) != -1){
							   IncreasePushCount(callback);
							}
						}
					});
				}
			}
		})
	}
};
function IncreasePushCount(callback){
	var data = {};
	data.Act="Add_PushCount";
	Post(data, json=>{
		if(callback){callback(json);}
	});
};

function AutoLogin(){
	wx.login({
	  success: async res => {
		console.log("唯一",res.code)	
	  }
	})
};

function MatcherIsIdentify(){
	if(uni.getStorageSync("Role")=="1" && uni.getStorageSync("IsIdentify")=="0"){
		Confirm("请进行实名认证，才可以为单身男女提供志愿服务。", ()=>{
			uni.navigateTo({
				url:'/pages/index/identify_matcher'
			})
		});
	}
};

module.exports = {
  Domain,
  FormatTime,
  Alert,
  Confirm,
  Toast,
  Success,
  Fail,
  Loading,
  HideLoading,
  Upload,
  OneUpload,
  Post,
  GetQueryString,
  GCJ02ToBaiDu,
  SetTabBarBadge,
  ListToImgs,
  ListToPaths,
  TranList,
  LoadMore,
  CheckUpdate,
  DateDiff,
  SetParam,
  AdSkip,
  Auth,
  ClearForm,
  ToSuccess,
  ToPaySuccess,
  GetMenuHeight,
  navigateTo,
  AddPushCount,
  AutoLogin,
  MatcherIsIdentify
}